<!-- @author zhengjie -->
<template>
  <div>
    <div @click="openPickDeptUser">
      <el-input v-model="userName" readonly placeholder="请选择" class="w-100">
      </el-input>
    </div>

    <el-dialog
      title="选择人员"
      :visible.sync="TreedialogVisible"
      width="720px"
      append-to-body
    >
      <div class="append-class">
        <el-form ref="queryParamsForm" :model="queryParams" label-width="80px">
          <div v-for="(domain, index) in queryParams.domains" :key="index">
            <el-form-item
              :label="'人员' + (index + 1)"
              :key="domain.key"
              :prop="'domains.' + index + '.userId'"
              :rules="{
                required: true,
                message: '人员不能为空',
                trigger: 'blur',
              }"
            >
              <div class="domains-item">
                <el-row>
                  <el-col :span="12">
                    <deptItem
                      class="w-100"
                      v-model="domain.deptId"
                      :options="deptOptions"
                      @change="(value) => changeDepid(value, index)"
                    ></deptItem>
                  </el-col>
                  <el-col :span="12">
                    <el-select
                      class="w-100"
                      v-model="domain.userId"
                      filterable
                      :multiple="multiple"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in domain.userArry"
                        :key="item.id"
                        :label="item.nickname"
                        :value="item.id"
                      >
                      </el-option> </el-select
                  ></el-col>
                </el-row>

                <div
                  class="domains-item-op"
                  v-show="queryParams.domains.length > 1"
                >
                  <el-button @click.prevent="removeDomain(domain)"
                    >删除</el-button
                  >
                </div>
              </div>
            </el-form-item>
          </div>

          <div class="add-domain" v-if="queryParams.domains.length < maxSize">
            <el-button @click="addDomain">新增人员</el-button>
          </div>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeCC()">取 消</el-button>
        <el-button type="primary" @click="surePost()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
  
  <script>
import deptItem from "./deptItem";
import { listSimpleDepts } from "@/api/system/dept";
import { listUser } from "@/api/system/user";
import { map } from "min-dash";

export default {
  name: "pickDeptUser",
  props: {
    multiple: {
      type: Boolean,
      default: true,
    },
    maxSize: {
      type: Number,
      default: 999,
    },

    value: {
      type: String,
      default: "",
    },

    arry: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  components: {
    deptItem,
  },
  data() {
    return {
      TreedialogVisible: false,
      queryParams: {
        domains: [
          {
            deptId: undefined,
            userId: [],
            userArry: [],
            userObj: {},
          },
        ],
      },

      userName: "",

      deptOptions: [],
      userListObj: {},
      userList: [],
    };
  },

  watch: {
    arry: {
      immediate: true,
      handler(newValue, oldValue) {
        if (!newValue || newValue.length === 0) {
          this.queryParams.domains = [
            {
              deptId: undefined,
              userId: this.multiple ? [] : "",
              userArry: [],
              userObj: {},
            },
          ];
        } else {
          this.queryParams.domains = newValue;
        }
      },
    },
  },

  methods: {
    clear(){
      this.queryParams.domains = [
            {
              deptId: undefined,
              userId: this.multiple ? [] : "",
              userArry: [],
              userObj: {},
            },
          ];
    },
    setName(val) {
      this.userName = val;
      this.$forceUpdate();
    },
    openPickDeptUser() {
      this.TreedialogVisible = true;
      this.getTreeselect();
    },

    closeCC() {
      this.TreedialogVisible = false;
    },

    open() {
      this.TreedialogVisible = true;
      this.getTreeselect();
    },

    getTreeselect() {
      listSimpleDepts().then((response) => {
        // 处理 deptOptions 参数
        this.deptOptions = [];
        this.deptOptions.push(...this.handleTree(response.data, "id"));
      });
    },

    removeDomain(item) {
      var index = this.queryParams.domains.indexOf(item);
      if (index !== -1) {
        this.queryParams.domains.splice(index, 1);
      }
    },
    addDomain() {
      this.queryParams.domains.push({
        deptId: undefined,
        userId: this.multiple ? [] : "",
        userArry: [],
        userObj: {},
        key: Date.now(),
      });
    },

    changeDepid(val, index) {
      listUser({
        pageNo: 1,
        pageSize: 100,
        deptId: val,
      }).then((response) => {
        let userList = response.data.list;
        let userListObj = {};
        for (let i = 0; i < userList.length; i++) {
          let userItem = userList[i];
          userListObj[userItem.id] = userItem;
        }
        this.queryParams.domains[index].userArry = userList;
        this.queryParams.domains[index].userObj = userListObj;
      });
    },

    surePost() {
      this.$refs["queryParamsForm"].validate((valid) => {
        if (valid) {
          //
          // let values = domains.map((item) => {
          //   return item.userId;
          // });

          // let ids = values.map((item) => {
          //   return item.join(",");
          // });

          const domains = this.queryParams.domains;
          let ids = [];
          let userName = [];
          for (let i = 0; i < domains.length; i++) {
            let item = domains[i];
            if (this.multiple) {
              ids = ids.concat(item.userId);
              for (let n = 0; n < item.userId.length; n++) {
                if (!!item.userObj[item.userId[n]]) {
                  userName.push(item.userObj[item.userId[n]].nickname);
                }
              }
            }else{
              ids.push(item.userId)
              userName.push(item.userObj[item.userId].nickname);
            }
          }

          this.userName = userName.join(",");
          this.$emit("change", ids.join(","));

          // this.$emit("changeuser", this.queryParams.userId);
          // if (this.userListObj[this.queryParams.userId]) {
          //   this.queryParams.userName =
          //     this.userListObj[this.queryParams.userId].nickname;
          // }
          this.closeCC();
        } else {
          return false;
        }
      });
    },
  },

  model: { prop: "value", event: "change" },
};
</script>
  
  <style rel="stylesheet/scss" lang="scss" scoped>
.append-class {
  min-height: 200px;
}

.domains-item {
  position: relative;
  padding-right: 100px;
  .domains-item-op {
    position: absolute;
    top: 0px;
    right: 0px;
  }
}

.add-domain {
  padding-left: 80px;
}
</style>
  